import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:get/get.dart';


import '../logic/file_manager.dart';
import '../logic/network_request.dart';
import 'sign_apk_event.dart';
import 'sign_apk_state.dart';
import 'package:dio/dio.dart' as Dio;

class SignApkBloc extends Bloc<SignApkEvent, SignApkState> {
  SignApkBloc() : super(SignApkState().init()) {
    on<InitEvent>(_init);
    on<SignEvent>(_sign);
    on<CancelSignEvent>(_cancel);
  }

  void _init(InitEvent event, Emitter<SignApkState> emit) async {
    emit(state.init());
  }

  void _sign(SignEvent event, Emitter<SignApkState> emit) async {
    printInfo(info: "_sign:${event.apkPath}___${event.signTypeName}");
    NetworkRequestManager networkRequestManager = NetworkRequestManager();
    String url = "http://10.150.99.28:8081/sign/api/resign_apk/";
    emit(state.copyWith(SignStatus.startUpload));
    var response = await networkRequestManager.signApkWithCallback(
        url, event.apkPath, event.signTypeName, (sent, total) {
      printInfo(info: "sentCallback $sent - $total");
      if (sent < total) {
        emit(state.copyWith(SignStatus.uploading,
            uploadProgress: sent * 1.0 / total));
      } else {
        emit(state.copyWith(SignStatus.uploaded, uploadProgress: 1.0));
        Timer(const Duration(milliseconds: 100), () {
          emit(state.copyWith(SignStatus.startSign, uploadProgress: 1.0));
        });
      }
    }, (count, total) {});
    printInfo(info: "value:$response");
    if (response.statusCode == 200) {
      emit(state.copyWith(SignStatus.signSuccess, uploadProgress: 1.0));
      var fileManager = FileManager();
      var result = await fileManager.saveFile(event.apkPath, response.data);
      if (result == 1) {
        emit(state.copyWith(SignStatus.downloadSuccess, uploadProgress: 1.0));
      }
    }
  }

  void _cancel(CancelSignEvent event, Emitter<SignApkState> emit) async {
    emit(state.copyWith(SignStatus.ideal));
  }
}
